---------------------------------------------------------------
-- @Description：         agent
---------------------------------------------------------------
local skynet = require "skynet"
local log = require "sky_log"
local handle_robot = require "handle_robot"
local cc = require  "sky_call"

local timer_thread
local robot_agent = {
	client_fd = nil,
	watchdog = nil,
	gate = nil,
	agent_info = nil,
}

local MESSAGE_CGATE_TYPE = 101
skynet.register_protocol {
    name = "cgate_msg",
    id = MESSAGE_CGATE_TYPE,
    pack = function(msg)
        local str = ''
        if type(msg)~='table' then 
            str = tostring(msg)
        else
            for _, v in ipairs(msg) do 
                str=str..v.."#"
            end
        end
		--log.info("cgate pack str=", str)
        return str
    end,
    unpack = skynet.tostring,
    dispatch = function(session, from, message, sz) end
}

skynet.register_protocol {
	name = "client",
	id = skynet.PTYPE_CLIENT,
	unpack = function (msg, sz)
		return msg, sz
	end,
	dispatch = function (session, address, msg, sz)
		skynet.ignoreret()
		local f = handle_robot["dispatch_msg"]
		f(robot_agent.agent_info, robot_agent.client_fd, msg, sz)
	end
}

--============================= Local Function =============================--
local function init()
    --log.info("service_robot init!")
end 

local function start_timer()
	--timer_thread = skynet.timeout(100, start_timer)
	timer_thread = skynet.fork(function ()
		while true do
			skynet.sleep(100)
			handle_robot["do_timer"]()
		end
	end)
end

local function stop_timer()
	--log.info("stop_timer timer_thread=", timer_thread)
	skynet.killthread(timer_thread)
end

local function login()
	--log.info("service_robot do_login!  agent= ", skynet.self())

	local f = handle_robot["do_login"]

	f(robot_agent.agent_info, robot_agent.client_fd)
end

local function logout()
	--log.info("service_robot do_logout!  agent= ", skynet.self())

	local f = handle_robot["do_logout"]

	f(robot_agent.agent_info, robot_agent.client_fd)
end

--============================= CMD =============================--
local CMD = {}

function CMD.connect_server(agent_data)
	--log.info("connect_server info= ", agent_data)

	if not agent_data 
	or not agent_data.config_info.server_ip
	or not tonumber(agent_data.config_info.server_port)
	or not agent_data.agent then 
		log.error("robot_manager--->agent error! connect_server info= ", agent_data)
	end
	
	robot_agent.agent_info = agent_data
	local msg_t = {
		"connect",
		agent_data.config_info.server_ip, 
		tonumber(agent_data.config_info.server_port),
		agent_data.agent,
	}

	cc.send_cgate(msg_t)
end

function CMD.connected(msg)
    --log.info("service_robot connected! msg=", msg)
	--start_timer()
    robot_agent.watchdog = msg.watchdog
    robot_agent.gate = msg.gate
	robot_agent.client_fd = msg.fd
	--log.info("robot_agent=", robot_agent)

	local sleep_t = math.random(100, 300)
	skynet.timeout(sleep_t, login)
end 

function CMD.disconnect_server()
	logout()
	cc.send_cgate( {"kick", robot_agent.client_fd})
end

function CMD.disconnect()
    --log.info("service_robot disconnect!  agent= ", skynet.self())
	
	stop_timer()
	robot_agent = {}
    skynet.exit()
end 

function CMD.debug_get_infos()
	log.warning("robot_agent=", robot_agent)
end

skynet.start(function()
    skynet.dispatch("lua", function(session, address, cmd, ...)
        local f = CMD[cmd]
		--log.debug("cmd=", cmd)
        if f then
            skynet.ret(skynet.pack(f(...)))
        else
            error(string.format("Unknown command %s", tostring(cmd)))
        end
    end)

    init()
end)